package org.xsk.network.http;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.infra.Blackhole;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
@BenchmarkMode(Mode.AverageTime)
public class HttpClient {

    @Benchmark
    public String client_1(){
        HttpURLConnection con ;
        BufferedReader buffer ;
        StringBuffer result ;

        try {
            URL url = new URL("http://localhost:9200/");
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod(HttpParameter.RequestMethod.POST.name());
            con.setRequestProperty(HttpParameter.ContentType.DEFAULT.name(),HttpParameter.ContentType.DEFAULT.getValue());
            con.setDoOutput(Boolean.TRUE);
            con.setDoInput(Boolean.TRUE);
            con.setUseCaches(Boolean.FALSE);
            OutputStream outputStream = con.getOutputStream();
            outputStream.write("".getBytes());
            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK){
                InputStream inputStream = con.getInputStream();
                buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
                String line;
                result = new StringBuffer();
                while ( (line = buffer.readLine()) != null){
                    result.append(line);
                }
                System.out.println(line);
                return result.toString();
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return null;
    }
}
